package com.unknownman.block.annotation;


import com.lianziyou.chain.common.constants.MQConstants;
import com.lianziyou.chain.common.utils.RabbitMetaMessage;
import com.unknownman.block.rabbitmq.send.RabbitSender;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;


@Aspect
@Slf4j
public class TransactionSenderAspect {

    RabbitSender rabbitSender;

    public TransactionSenderAspect(RabbitSender rabbitSender) {
        this.rabbitSender = rabbitSender;
    }

    /**
     * 定义注解类型的切点，只要方法上有该注解，都会匹配
     */
    @Pointcut("execution(* com.unknownman.block.rabbitmq.send.*.*(..)) && @annotation(com.unknownman.block.annotation.TransMessage)")
    public void annotationSender() {
    }

    @SuppressWarnings("unchecked")
    @Around("annotationSender()&& @annotation(rd)")
    public void sendMsg(ProceedingJoinPoint joinPoint, TransMessage rd) throws Throwable {
        String exchange = rd.exchange();
        String routeKey = rd.routeKey();
        String bizName = rd.bizName();

        Object returnObj = null;
        /** 执行业务函数 */
        try {
            returnObj = joinPoint.proceed();
        } catch (Exception ex) {
            log.error("业务执行失败,业务名称:" + bizName);
            throw ex;
        }

        if (returnObj == null) {
            returnObj = MQConstants.BLANK_STR;
        }

        /** 生成一个发送对象 */
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();

        rabbitMetaMessage.setMessageId(bizName);
        /**设置交换机 */
        rabbitMetaMessage.setExchange(exchange);
        /**指定routing key */
        rabbitMetaMessage.setRoutingKey(routeKey);
        /** 设置需要传递的消息体,可以是任意对象 */
        rabbitMetaMessage.setPayload(returnObj);

        /** 发送消息 */
        try {
            rabbitSender.send(rabbitMetaMessage);
        } catch (Exception e) {
            log.error("第一阶段消息发送异常" + bizName + e);
            throw e;
        }
    }

}
